﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using BlueLotus7.WeiboApiLibrary.Weibo.Contracts;
using System.Xml.Linq;
using BlueLotus7.Common;

namespace BlueLotus7.WeiboApiLibrary
{
    partial class ContentAnalyzer
    {
        #region TranslateWeiboArticleSummaryHtml

        internal static List<WeiboArticle> TranslateWeiboArticlesForHome(string htmlContent, ref bool hasNextPage)
        {
            return TranslateWeiboArticlesForHome(htmlContent, ref hasNextPage, null, null);
        }

        /// <summary>
        /// Translates Weibo articles for home page content.
        /// </summary>
        /// <param name="htmlContent">Html content</param>
        /// <param name="hasNextPage">Reference boolean flag to indicate whether has next page.</param>
        /// <param name="callback">Delegate for each <c>WeiboArticle</c> translated.</param>
        /// <param name="callbackObject">Object for delegate.</param>
        /// <returns>List of <c>WeiboArticle</c> instances.</returns>
        internal static List<WeiboArticle> TranslateWeiboArticlesForHome(string htmlContent, ref bool hasNextPage, WeiboArticleDelegate callback, object callbackObject)
        {
            List<WeiboArticle> articles = new List<WeiboArticle>();

            if (!string.IsNullOrWhiteSpace(htmlContent))
            {
                htmlContent = CleanHtmlContent(htmlContent);

                try
                {
                    XElement xElement = XDocument.Parse(htmlContent).Root;
                    articles = TranslateWeiboArticlesForHome(xElement, ref hasNextPage, callback, callbackObject);
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to parse cleaned html content to xml. Html content:" + (string.IsNullOrWhiteSpace(htmlContent) ? string.Empty : htmlContent), ex);
                }
            }

            return articles;
        }

        private static List<WeiboArticle> TranslateWeiboArticlesForHome(XElement bodyNode, ref bool hasNextPage, WeiboArticleDelegate callback, object callbackObject)
        {
            List<WeiboArticle> result = new List<WeiboArticle>();

            return result;
        }

        private static WeiboArticle TranslateWeiboArticleSummaryHtmlForHome(XElement divNode, WeiboArticleDelegate callback, object callbackObject)
        {
            WeiboArticle article = null;

            if (article != null && callback != null)
            {
                InvokeDelegate(article, callback, callbackObject);
            }

            return article;
        }

        #endregion




        private static WeiboArticle TranslateWeiboArticleSummaryHtml(string htmlContent)
        {
            WeiboArticle article = null;

            if (!string.IsNullOrWhiteSpace(htmlContent))
            {
                article = new WeiboArticle();


            }

            return article;
        }

        private static WeiboArticle TranslateWeiboArticleDetailHtml(string htmlContent)
        {
            WeiboArticle article = null;

            if (!string.IsNullOrWhiteSpace(htmlContent))
            {
                htmlContent = CleanHtmlContent(htmlContent);

                article = new WeiboArticle();


            }

            return article;
        }

        //<div class="c" id="C_3420259237655828">
        //<a href="/13861201?vt=4&amp;gsid=3_5bc353f8e36c2c83509a65bbeb0af98e0a435261">鱼丸一世</a>:<span
        //    class="ctt">回复<a href="/n/%E6%9C%AB%E6%9C%88de%E9%B1%BC?vt=4&amp;gsid=3_5bc353f8e36c2c83509a65bbeb0af98e0a435261">@末月de鱼</a>:。。。。。下作呸！</span>&nbsp;<span
        //        class="cc"><a href="/comments/reply/y8uUXxOS5/3420259237655828?rl=1&amp;vt=4&amp;gsid=3_5bc353f8e36c2c83509a65bbeb0af98e0a435261">回复</a></span>&nbsp;<span
        //            class="ct">03月05日 16:40&nbsp;来自新浪微博</span></div>
        private static WeiboArticle TranslateWeiboArticleCommentHtml(XmlNode divNode, Guid articleGuid, List<WeiboArticle> commentsClain, WeiboContentRetriever retirever)
        {
            const string errorInvalidCommentId = "Invalid article comment ID.";
            const string errorInvalidCommentOwnerId = "Invalid article comment owner ID.";
            const string errorInvalidCommentOwner = "Comment owner not found for {0}.";
            const string errorInvalidPreviousCommentOwner = "Invalid article previous comment owner ID.";
            const string errorInvalidTimeAgentSign = "Invalid time and agent signs.";

            WeiboArticle comment = null;
            if (divNode != null)
            {
                //Comment ID
                string commentId = GetXmlAttributeValue(divNode, tag_id);
                if (string.IsNullOrWhiteSpace(commentId) || commentId.StartsWith("C_"))
                {
                    throw new Exception(errorInvalidCommentId);
                }

                commentId = commentId.Substring(2, commentId.Length - 2);
                comment = new WeiboArticle();
                comment.ContentType = WeiboArticle.WeiboContentType.WeiboComments;

                //Owner
                string ownerLink = GetXmlAttributeValue(divNode.ChildNodes[0], tag_href);
                if (string.IsNullOrWhiteSpace(ownerLink))
                {
                    throw new Exception(errorInvalidCommentOwnerId);
                }

                int index = ownerLink.IndexOf('?');
                if (index < 0)
                {
                    throw new Exception(errorInvalidCommentOwnerId);
                }

                string ownerIdentity = ownerLink.Trim('/').Substring(0, index);
                long ownerUid = 0;
                if (string.IsNullOrWhiteSpace(ownerIdentity) || long.TryParse(ownerIdentity, out ownerUid))
                {
                    throw new Exception(errorInvalidCommentOwnerId);
                }

                //Previous Comment Owner
                XmlNode commentToTargetNode = divNode.SelectSingleNode("descendant::span[@class='" + class_CommentToTarget + "']");
                XmlNode previousCommentUserNode = commentToTargetNode.SelectSingleNode("descendant::a");
                if (previousCommentUserNode == null)
                {
                    throw new Exception(errorInvalidPreviousCommentOwner);
                }

                ownerLink = GetXmlAttributeValue(previousCommentUserNode, tag_href);
                if (string.IsNullOrWhiteSpace(ownerLink))
                {
                    throw new Exception(errorInvalidPreviousCommentOwner);
                }

                commentToTargetNode.RemoveChild(previousCommentUserNode);
                string commentContent = commentToTargetNode.InnerText.Substring(content_replyConstString.Length);
                comment.TextContent = commentContent;

                XmlNode timeAgentNode = divNode.SelectSingleNode("descendant::span[@class='" + class_CommentTime + "']");
                if (timeAgentNode == null)
                {
                    throw new Exception(errorInvalidTimeAgentSign);
                }

                string[] agentParts = timeAgentNode.InnerText.Split(new string[] { html_space }, StringSplitOptions.RemoveEmptyEntries);
                comment.Agent = agentParts[1].Substring(content_fromConstString.Length);
                comment.CreatedStamp = Convert.ToDateTime(agentParts[0]);
            }
            return comment;
        }


    }
}
